import Constants from '@/api/constants'
import {
  paramsToQueryString
} from './index'
export default function request({
  method = 'post',
  data = {},
  url,
  params
}) {
  console.log('MXCommon.ajax', url)
  return new Promise(function (resolve, reject) {
    console.log(1)
    document.addEventListener('deviceready', function () {
      console.log(2)
      MXCommon.ajax({
        type: method,
        url: `${Constants.buildServerUrl}${url}${params ? `&${paramsToQueryString(params)}` : ''}`,
        dataType: "json",
        data,
        headers: {
          "Content-Type": "application/json;charset=utf-8",
        },
        async: true,
        complete: function () {
          console.log(3)
        },
        success: function (response, status, xhr) {
          console.log(4)
          const res = JSON.parse(response)
          resolve(res.result ? res.result : res)
        },
        error: function (error, status, xhr) {
          console.log(5, error, status)
          console.log(`${Constants.buildServerUrl}${url}`)
          switch (status) {
            case 400:
              vm.$dialog.alert({
                title: '发生错误',
                message: error
              })
              break
            case 401:
              vm.$dialog.alert({
                title: '权限错误',
                message: error
              })
              break
            case 405:
            case 404:
              vm.$dialog.alert({
                title: 'http请求方式有误',
                message: error
              })
              break
            case 500:
              vm.$dialog.alert({
                title: '服务器出了点小差，请稍后再试',
                message: error
              })
              break
            case 501:
              vm.$dialog.alert({
                title: '服务器不支持当前请求所需要的某个功能',
                message: error
              })
              break
            case 504:
              vm.$dialog.alert({
                title: '服务器链接超时',
                message: error
              })
              break
            case -1001:
              vm.$dialog.alert({
                title: '服务器链接超时',
                message: error
              })
              break
          }
          reject(err)
        }
      })
    })
  })
}